// pages/index/designer_detail.js
var app = getApp();
var call = require("../../utils/request.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winHeight: "", //窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    // tab切换
    toView: '',
    name: '虎宝宝',
    companyname: '暂无公司',
    job: '暂无职位',
    average: '空',
    address: '暂无地址',
    phone: '暂无联系方式',
    canvasUrl: '',
    downimg: '',
    cover: '../../images/free/card.png',
    avar: '',
    imgurl: '',
    imgurls: '',
    cards: true,
    id: '',
    downqcode: '',
    canvasback: '',
    hidecode: true,
    showcode: false,
    card: '获取验证码',
    sid: '',
    infotele: '',
    telepho: '',
    fans: '',
    showcanvas: true
  },
  canvasId: "qrcCanvas",

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var id = options.id
    var scene = decodeURIComponent(options.id);
    if (typeof(options.scene) != "undefined") {
      var id = decodeURIComponent(options.scene)
    } else {
      var id = options.id
    }
    console.log(id)
    wx.request({
      url: app.apiUrl('c=shejishi/index&a=getdetail'),
      data: {
        designerID: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      success: function(res) {
        console.log(res.data)
        var polist = res.data.data
        var netUrl = polist.avatar
        var companyNmae = polist.companyName
        var job = polist.jobValue
        var average = polist.averagePrice
        var provice = polist.provinceValue
        console.log(provice)
        var address = polist.siteValue
        var phone = polist.phone
        var fans = polist.fans
        var phones = phone.replace(/(\d{3})(\d{4})/, "$1 $2 ");
        var length = polist.rend.length
        //console.log(length)
        var swiperH = length * 750 + 60
        if (companyNmae == null) {
          var text = '暂无公司'
          that.setData({
            companyname: text,
            polist: polist,
            job: job,
            average: average,
            address: address,
            provice:provice,
            phone: phones,
            avar: netUrl,
            fans: fans,
            winHeight: swiperH
          })
        } else {
          that.setData({
            polist: polist,
            companyname: companyNmae,
            job: job,
            average: average,
            address: address,
            provice: provice,
            phone: phone,
            avar: netUrl,
            fans: fans,
            winHeight: swiperH
          })
        }
        wx.setNavigationBarTitle({
          title: companyNmae //页面标题为路由参数
        })
        // wx.getImageInfo({ //保存网络图片
        //   src: 'c=shejishi/index&a=getdetail',
        //   success: function(res) {
        //     console.log(res.path)
        //     //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
        //   }
        // })
        //下载图片
        that.downLoading()
        that.downQcode()
        that.downcanba()
        setTimeout(function() {
          that.canvasImg()
          //that.throwcard()
        }, 1000)
      },
      fail: function(res) {
        console.log('请求失败', res.data)
      }
    })
    wx.showShareMenu({
      // 要求小程序返回分享目标信息
      withShareTicket: true
    });
    //that.getdevice()
    setTimeout(function() {
      that.initcode()
    }, 200)
    that.setData({
      id: id
    })
    call.getData('session', this.shuffleSuc, this.fail);
  },
  //获取session
  shuffleSuc: function(res) {
    //console.log(res)
    var that = this;
    var sid = res.data.PHPSESSID
    wx.setStorage({ //存储到本地
      key: "sid",
      data: sid
    })
    that.setData({
      sid: sid
    })
  },
  fail: function() {
    console.log("失败")
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  // 点击标题切换当前页时改变样式
  swichNav: function(e) {
    var that = this
    var cur = e.target.dataset.current;
    if (this.data.currentTaB == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
    console.log(cur)
  },
  // 滚动切换标签样式
  switchTab: function(e) {
    var that = this
    var index = e.detail.current 
    var polist = that.data.polist
    var length = polist.rend.length
    var winHeight = length * 750 + 60
    //swiper自动高度设置
    var query = wx.createSelectorQuery();
    query.select('#detail').boundingClientRect()
    if (index == 0) {
      //console.log(winHeight)
      that.setData({
        winHeight: winHeight
      })
    } else {
      query.exec(function(res) {
        //res就是 所有标签为mjltest的元素的信息 的数组
        //console.log(res);
        //取高度
        var height = res[0].height * 2 + 180
        //console.log(res[0].height);
        that.setData({
          winHeight: height
        })
      })

    }
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();

  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function() {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  sharecard: function(e) {
    this.setData({
      sharemodel: true
    })
  },
  skipTop: function(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  //下载网络图片
  downLoading: function() {
    var that = this
    var avatar = that.data.avar
    wx.downloadFile({
      url: avatar,
      success: function(res) {
        if (res.statusCode === 200) {
          //console.log('下载图片成功');
          that.setData({
            downimg: res.tempFilePath
          })
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  downQcode: function() {
    var that = this
    var id = that.data.id
    wx.downloadFile({
      url: app.apiUrl('c=shejishi/index&a=getqrcode&designerID=' + id),
      success: function(res) {
        if (res.statusCode === 200) {
          //console.log('下载二维码成功');
          that.setData({
            downqcode: res.tempFilePath
          })
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  downcanba: function() {
    var that = this
    var id = that.data.id
    wx.downloadFile({
      url: 'https://img.xtuan.com/xcximgtest/images/free/card.png',
      success: function(res) {
        if (res.statusCode === 200) {
          //console.log('下载背景图');
          that.setData({
            canvasback: res.tempFilePath
          })
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  //进行绘图
  canvasImg: function(res) {
    var that = this
    var name = that.data.polist.designerName
    console.log(name)
    var companyname = that.data.companyname
    console.log(companyname)
    var job = that.data.job
    var average = that.data.average
    var address = that.data.address
    var provice = that.data.provice
    var phone = that.data.phone
    var fans = parseInt(that.data.fans)
    if (companyname == null) {
      var companyname = '暂无公司'
    }
    if (phone == null) {
      var phone = '暂无电话'
    }
    if ((name == undefined) || (name == null)) {
      name = '暂无填写'
    }
    var downqcode = that.data.downqcode
    var canvasback = that.data.canvasback
    console.log(downqcode)
    var img = that.data.avar
    var rpx;
    wx.getSystemInfo({
      success: function(res) {
        rpx = res.windowWidth / 375;
      },
    })
    const ctx = wx.createCanvasContext('Canvascard')
    var avatarurl_width = 500; //这个是画布宽
    var avatarurl_heigth = 300;
    var imgurl = that.data.imgurl
    var downimg = that.data.downimg
    if(fans==0){
      ctx.beginPath()
      //ctx.drawImage(canvasback, 0, 0, 700 * rpx, 200 * rpx);
      ctx.setFillStyle('white')
      ctx.fillRect(0, 0, 750 * rpx, 200 * rpx)
      ctx.save();
      ctx.arc(65 * rpx, 63 * rpx, 35 * rpx, 0, Math.PI * 2,false);
      ctx.clip();
      ctx.drawImage(downimg, 30 * rpx, 28 * rpx, 70 * rpx, 70 * rpx) //左边图像
      ctx.restore();
      ctx.setFillStyle('black')
      ctx.setFontSize(16 * rpx)
      ctx.fillText(name, 110 * rpx, 50 * rpx)
      ctx.setTextAlign('left')
      ctx.restore();
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.setFontSize(12 * rpx)
      ctx.fillText(companyname, 110 * rpx, 80 * rpx)
      ctx.restore();
      ctx.drawImage('../../images/free/authen.png', 270 * rpx, 68 * rpx, 20 * rpx, 15 * rpx)
      ctx.restore();
      ctx.drawImage(downqcode, 300 * rpx, 28 * rpx, 70 * rpx, 70 * rpx) //右边图像
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(provice, 30 * rpx, 140 * rpx)
      ctx.restore();
      ctx.fillText('·', 57 * rpx, 140 * rpx)
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(address, 62 * rpx, 140 * rpx)
      ctx.restore();
      ctx.drawImage('../../images/free/xieimg.png', 290 * rpx, 125 * rpx, 80 * rpx, 15 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('white')
      ctx.fillText(job, 300 * rpx, 137 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(phone, 30 * rpx, 160 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText(average, 300 * rpx, 160 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.setTextAlign('left')
      ctx.fillText('/m²', 320 * rpx, 160 * rpx)
      ctx.restore();
      ctx.setFontSize(14 * rpx)
      ctx.setFillStyle('white')
      ctx.draw()
      that.setData({
        cheight: 480
      })
    }else{
      ctx.beginPath()
      ctx.drawImage(canvasback, 0, 0, 750 * rpx, 300 * rpx);
      ctx.save();
      ctx.arc(65 * rpx, 63 * rpx, 35 * rpx, 0, Math.PI * 2, false);
      ctx.clip();
      ctx.drawImage(downimg, 30 * rpx, 28 * rpx, 70 * rpx, 70 * rpx) //左边图像
      ctx.restore();
      ctx.setFillStyle('black')
      ctx.setFontSize(16 * rpx)
      ctx.fillText(name, 110 * rpx, 50 * rpx)
      ctx.setTextAlign('left')
      ctx.restore();
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.setFontSize(12 * rpx)
      ctx.fillText(companyname, 110 * rpx, 80 * rpx)
      ctx.restore();
      ctx.drawImage('../../images/free/authen.png', 270 * rpx, 68 * rpx, 20 * rpx, 15 * rpx)
      ctx.restore();
      ctx.drawImage(downqcode, 300 * rpx, 28 * rpx, 70 * rpx, 70 * rpx) //右边图像
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(provice, 30 * rpx, 140 * rpx)
      ctx.restore();
      ctx.fillText('·', 57 * rpx, 140 * rpx)
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(address, 30 * rpx, 140 * rpx)
      ctx.restore();
      ctx.drawImage('../../images/free/xieimg.png', 290 * rpx, 125 * rpx, 80 * rpx, 15 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('white')
      ctx.fillText(job, 300 * rpx, 137 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(phone, 30 * rpx, 160 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText(average, 300 * rpx, 160 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.setTextAlign('left')
      ctx.fillText('/m²', 320 * rpx, 160 * rpx)
      ctx.restore();
      ctx.setFontSize(14 * rpx)
      ctx.setFillStyle('white')
      ctx.fillText('我们一共服务业主', 30 * rpx, 220 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText('312', 145 * rpx, 220 * rpx)
      ctx.setFillStyle('white')
      ctx.fillText('名', 170 * rpx, 220 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText(',  超过', 185 * rpx, 220 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText('42.74%', 220 * rpx, 220 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText('的同行', 265 * rpx, 220 * rpx)
      ctx.fillText('共创作了', 30 * rpx, 240 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText('10', 80 * rpx, 240 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText('个设计作品，', 100 * rpx, 240 * rpx)
      ctx.restore();
      ctx.setFontSize(12 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText('获得了', 30 * rpx, 260 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText('12812', 70 * rpx, 260 * rpx)
      ctx.setFillStyle('rgb(153,153,153)')
      ctx.fillText('的人气，', 110 * rpx, 260 * rpx)
      ctx.fillText('排行前', 160 * rpx, 260 * rpx)
      ctx.setFillStyle('rgb(255,96,0)')
      ctx.fillText('30%', 200 * rpx, 260 * rpx)
      ctx.restore();
      ctx.draw()
      that.setData({
        cheight:680
      })
    }
    setTimeout(function() {
      wx.hideLoading();
    }, 1000)
    setTimeout(function() {
      that.throwcard()
    }, 200)

  },
  //将canvas转化为图片
  throwcard: function(e) {
    var that = this;
    wx.canvasToTempFilePath({
      // destWidth: 1200,  //生成图片的大小设置成canvas大小的二倍
      // destHeight: 1000,
      canvasId: 'Canvascard',
      success: function(res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        var arr = []
        arr.push(tempFilePath)
        that.setData({
          //showcanvas: false,
          canvasUrl: tempFilePath,
        })
        // wx.previewImage({
        //   current: res.tempFilePath, // 当前显示图片的http链接
        //   urls: [res.tempFilePath] // 需要预览的图片http链接列表
        // })
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //生成名片,发送给朋友
  gencard: function(e) {
    var that = this
    var avatar = that.data.polist.avatar
    // wx.showLoading({
    //   title: '正在生成名片...',
    // });
    // that.canvasImg()
    // that.throwcard()
    // that.setData({
    //   sharemodel: false
    // })
    var canvasUrl = that.data.canvasUrl
    console.log(canvasUrl)
    var arr = []
    arr.push(canvasUrl)
    wx.previewImage({
      current: canvasUrl, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
    that.setData({
      sharemodel: false
    })

  },
  //发送给朋友
  // sendfriend: function() {
  //   var that = this
  //   var canvasUrl = that.data.canvasUrl
  //   console.log(canvasUrl)
  //   var arr = []
  //   arr.push(canvasUrl)
  //   wx.previewImage({
  //     current: arr, // 当前显示图片的http链接
  //     urls: arr // 需要预览的图片http链接列表
  //   })
  //   that.setData({
  //     sharemodel: false
  //   })
  // },
  //分享给朋友按钮
  sendfriend: function () {
    this.setData({
      sharemodel: false
    })
  },
  //分享转发
  onShareAppMessage: function(ops) {
    var img = this.data.canvasUrl
    var id = this.data.id
    console.log(img)
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    return {
      // title: '自定义转发标题',
      //imageUrl: '../../images/free/user1.png',
      path: 'pages/index/designer_detail?id=' + id,
      success: function(res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
        var shareTickets = res.shareTickets;
      },
      fail: function(res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
    this.setData({
      sharemodel: false
    })
  },
  //初始获取验证码
  initcode: function() {
    var that = this
    var sid = that.data.sid
    //console.log('奥术大师', sid)
    var text = '获取验证码'
    wx.request({
      url: app.apiUrl("c=zhaobiao/index&a=get_captcha"),
      //url: 'http://www.newx.com/api/weixinapp/?c=zhaobiao/index&a=get_captcha',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'PHPSESSID=' + sid
      },
      method: 'GET',
      success: function(res) {
        console.log(res.data)
        var code = res.data.datas.code
        that.setData({
          card: code,
          hidecode: false,
          showcode: true,
        })
        setTimeout(function() {
          that.setData({
            card: text,
          })
        }, 30000)
      }
    })
  },
  //预约输入判断
  bindKeyInput: function(e) {
    var value = e.detail.value
    var info = 1
    this.setData({
      info: info,
      hidecode: false,
      showcode: true,
      infotele: value
    })
  },
  designer: function() {
    this.setData({
      showModal: true,
      showinfo: true
    })
  },
  bindmask: function() {
    this.setData({
      showinfo: false,
      showModal: false
    })
  },
  settime: function() {
    var that = this
    setTimeout(function() {
      that.setData({
        alertmess: false
      })
    }, 2000)
  },
  //获取验证码
  getCode: function(e) {
    var that = this
    var text = '获取验证码'
    var tele = that.data.infotele
    var card = that.data.card
    var sid = that.data.sid
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (tele == '') {
      that.setData({
        alertmess: true,
        message: '请输入手机号码！'
      })
      that.settime()
    } else if (tele.length != 11) {
      that.setData({
        alertmess: true,
        message: '请重新输入手机号码！'
      })
      that.settime()
    } else if (!myreg.test(tele)) {
      that.setData({
        alertmess: true,
        message: '手机号码错误，请重新输入！'
      })
      that.settime()
    } else {
      wx.request({
        url: app.apiUrl('c=zhaobiao/index&a=get_captcha'),
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': 'PHPSESSID=' + sid
        },
        method: "GET",
        success: function(res) {
          console.log(res.data)
          var cards = res.data.datas.code
          //var landing_page = res.data.datas.landing_page
          console.log(cards)
          that.setData({
            card: cards,
            //land_page: landing_page,
            distate: false
          })
          setTimeout(function() {
            that.setData({
              card: text,
              distate: false
            })
          }, 60000)
        },
        fail: function(res) {
          console.log('请求失败', res.data)
        }
      })
    }
  },
  formSubmit: function(e) {
    var that = this
    var mobile = e.detail.value.mobile
    var code = e.detail.value.code
    var id = that.data.tid

    var thecode = that.data.card
    var land_page = that.data.land_page
    var sid = that.data.sid
    var basepeak = that.data.basepeak
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    console.log('提交', sid)
    console.log(thecode)
    var id = 1
    var title = '预约成功'
    var tsmall = '"恭喜您，预约成功，我们将尽快与您联系!'
    if (mobile == '') {
      that.setData({
        alertmess: true,
        message: '手机号码不能为空！'
      })
      that.settime()
    } else if (mobile.length != 11) {
      that.setData({
        alertmess: true,
        message: '请重新输入手机号码！'
      })
      that.settime()
    } else if (!myreg.test(mobile)) {
      that.setData({
        alertmess: true,
        message: '手机号错误，请重新输入！'
      })
      that.settime()
    } else if (code == '') {
      that.setData({
        alertmess: true,
        message: '验证码不能为空！'
      })
      that.settime()
    } else if (code != thecode) {
      that.setData({
        alertmess: true,
        message: '验证码不对！'
      })
      that.settime()
    } else {
      wx.request({
        url: app.apiUrl('c=zhaobiao/index&a=submit_bespeak_company'),
        data: {
          phone: mobile,
          code: code,
          company_id: id,
          landing_page: basepeak
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': 'PHPSESSID=' + sid
        },
        method: "POST",
        success: function(res) {
          console.log(res.data)
          var code = res.data.code
          var message = res.data.error
          if (code == 200) {
            wx.navigateTo({
              url: 'free/applysuccess?data=' + [id, title, tsmall],
            })
          } else {
            that.setData({
              alertmess: true,
              message: message
            })
            that.settime()
          }
        },
        fail: function(res) {
          console.log('请求失败', res.data)
        }
      })
      this.setData({
        showModal: false,
        Modalcontent: false,
        showinfo: false
      })
    }

    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  binddetail: function(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../impredra/impredra_detail?id=' + id,
    })
  },

  footerTap: app.footerTap
})